const User = require('../models/user.model');
const mongoose = require('mongoose');

/**
 * 获取用户列表 (管理员)
 * GET /api/admin/users
 */
exports.getUsers = async (req, res, next) => {
  try {
    const {
      keyword = '',
      role = '',
      status = '',
      isAdmin = '',
      page = 1,
      limit = 10,
      sort = '-createdAt'
    } = req.query;

    const pageNumber = parseInt(page);
    const limitNumber = parseInt(limit);
    const skip = (pageNumber - 1) * limitNumber;

    // 构建查询条件
    const query = {};

    // 关键词搜索
    if (keyword) {
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { email: { $regex: keyword, $options: 'i' } },
        { phone: { $regex: keyword, $options: 'i' } }
      ];
    }

    // 角色筛选
    if (role) {
      query.role = role;
    }

    // 状态筛选
    if (status) {
      query.status = status;
    }

    // 管理员筛选
    if (isAdmin !== '') {
      query.isAdmin = isAdmin === 'true';
    }

    // 获取总数
    const total = await User.countDocuments(query);

    // 获取用户列表
    const users = await User.find(query)
      .select('-password') // 不返回密码字段
      .sort(sort)
      .skip(skip)
      .limit(limitNumber);

    res.json({
      success: true,
      data: users,
      pagination: {
        current: pageNumber,
        pageSize: limitNumber,
        total,
        pages: Math.ceil(total / limitNumber)
      },
      total
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取用户详情 (管理员)
 * GET /api/admin/users/:id
 */
exports.getUser = async (req, res, next) => {
  try {
    const userId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(userId)) {
      return res.status(400).json({
        success: false,
        message: '无效的用户ID'
      });
    }

    const user = await User.findById(userId).select('-password');

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: user
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 创建用户 (管理员)
 * POST /api/admin/users
 */
exports.createUser = async (req, res, next) => {
  try {
    const {
      name,
      email,
      password,
      avatar,
      phone,
      role,
      isAdmin,
      status
    } = req.body;

    // 检查邮箱是否已存在
    const existingUser = await User.findOne({ email });
    if (existingUser) {
      return res.status(400).json({
        success: false,
        message: '邮箱已存在'
      });
    }

    // 创建用户
    const user = await User.create({
      name,
      email,
      password,
      avatar,
      phone,
      role,
      isAdmin: isAdmin || false,
      status: status || 'active'
    });

    // 返回用户信息（不包含密码）
    const userResponse = await User.findById(user._id).select('-password');

    res.status(201).json({
      success: true,
      data: userResponse,
      message: '用户创建成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 更新用户 (管理员)
 * PUT /api/admin/users/:id
 */
exports.updateUser = async (req, res, next) => {
  try {
    const userId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(userId)) {
      return res.status(400).json({
        success: false,
        message: '无效的用户ID'
      });
    }

    const updateData = { ...req.body };

    // 如果更新密码，需要加密
    if (updateData.password) {
      // 这里应该使用bcrypt加密密码，但为了简化示例，我们直接存储
      // 在实际项目中，应该在User模型的pre('save')中间件中处理密码加密
    }

    const user = await User.findByIdAndUpdate(
      userId,
      updateData,
      { new: true, runValidators: true }
    ).select('-password');

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: user,
      message: '用户更新成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 删除用户 (管理员)
 * DELETE /api/admin/users/:id
 */
exports.deleteUser = async (req, res, next) => {
  try {
    const userId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(userId)) {
      return res.status(400).json({
        success: false,
        message: '无效的用户ID'
      });
    }

    // 不能删除自己
    if (userId === req.user.id) {
      return res.status(400).json({
        success: false,
        message: '不能删除自己的账户'
      });
    }

    const user = await User.findByIdAndDelete(userId);

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      message: '用户删除成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 批量删除用户 (管理员)
 * POST /api/admin/users/batch-delete
 */
exports.batchDeleteUsers = async (req, res, next) => {
  try {
    const { ids } = req.body;

    if (!Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的用户ID列表'
      });
    }

    // 不能删除自己
    if (ids.includes(req.user.id)) {
      return res.status(400).json({
        success: false,
        message: '不能删除自己的账户'
      });
    }

    const result = await User.deleteMany({ _id: { $in: ids } });

    res.json({
      success: true,
      message: `成功删除 ${result.deletedCount} 个用户`
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 更新用户状态 (管理员)
 * PATCH /api/admin/users/:id/status
 */
exports.updateUserStatus = async (req, res, next) => {
  try {
    const userId = req.params.id;
    const { status } = req.body;

    if (!mongoose.Types.ObjectId.isValid(userId)) {
      return res.status(400).json({
        success: false,
        message: '无效的用户ID'
      });
    }

    if (!['active', 'inactive', 'banned'].includes(status)) {
      return res.status(400).json({
        success: false,
        message: '无效的状态值'
      });
    }

    const user = await User.findByIdAndUpdate(
      userId,
      { status },
      { new: true, runValidators: true }
    ).select('-password');

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: user,
      message: '用户状态更新成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取用户统计信息 (管理员)
 * GET /api/admin/users/stats
 */
exports.getUserStats = async (req, res, next) => {
  try {
    const totalUsers = await User.countDocuments();
    const activeUsers = await User.countDocuments({ status: 'active' });
    const bannedUsers = await User.countDocuments({ status: 'banned' });
    
    // 获取今天新注册的用户数
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const newUsersToday = await User.countDocuments({
      createdAt: { $gte: today }
    });

    res.json({
      success: true,
      data: {
        totalUsers,
        activeUsers,
        newUsersToday,
        bannedUsers
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 搜索用户 (管理员)
 * GET /api/admin/users/search
 */
exports.searchUsers = async (req, res, next) => {
  try {
    const { keyword, limit = 10 } = req.query;

    if (!keyword) {
      return res.json({
        success: true,
        data: []
      });
    }

    const users = await User.find({
      $or: [
        { name: { $regex: keyword, $options: 'i' } },
        { email: { $regex: keyword, $options: 'i' } },
        { phone: { $regex: keyword, $options: 'i' } }
      ]
    })
    .select('name email avatar phone')
    .limit(parseInt(limit));

    res.json({
      success: true,
      data: users
    });
  } catch (error) {
    next(error);
  }
};

module.exports = exports;
